package org.example.sword2offer.primary;

import java.util.ArrayList;

/**
 * @author: lynn
 * @Descript: 顺时针打印矩阵
 * @date: 2021/3/10 19:57
 * @version: 1.0
 */
public class Q19_Rerverse_PrintMatrix {  //逆顺序
    public static void main(String[] args) {
        int[][] array={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        System.out.println(printMatrix(array));
    }
    private static ArrayList<Integer> printMatrix(int [][] matrix) {  //逆时针打印矩阵
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
        int left = 0, top = 0, right = matrix.length - 1, bottom = matrix[0].length - 1;//m是行，n是列
        while(left < right && top < bottom){  //右下左上跑
            for (int i=top;i<bottom;i++) {
                res.add(matrix[i][right]);//向下
            }
            for (int i=left;i<right;i++) {
                res.add(matrix[top][i]); //向右
            }
            for (int i=bottom;i>top;i--) {
                res.add(matrix[i][left]);//向上
            }
            for (int i=right;i>left;i--) {
                res.add(matrix[bottom][i]);//向左
            }
            left++;top++;right--;bottom--; //跑完就缩圈
        }
        if(top==bottom){ // 剩余当行列
            for (int i=left;i<=right;i++) res.add(matrix[top][i]); // 直接遍历完
        }else if (left==right){
            for (int i=top;i<bottom;i++) res.add(matrix[i][right]);
        }
        return res;
    }

}
